<?php
session_start();

$lang = $_GET['lang'] ?? $_SESSION['lang'] ?? 'en';
$_SESSION['lang'] = $lang;

$lang_texts = [
    'en' => [
        'installation' => 'Installation',
        'fill_required_fields' => 'Please fill in all required fields.',
        'database_connection_failed' => 'Database connection failed: ',
        'installation_completed' => 'Installation completed successfully! Redirecting to main page...',
        'ai_website_installation' => 'lanxAI - 首个览星自研AI',
        'info_text' => 'Please fill in your database and API configuration details to complete the installation.',
        'database_host' => 'Database Host *',
        'database_name' => 'Database Name *',
        'database_username' => 'Database Username *',
        'database_password' => 'Database Password *',
        'api_base_url' => 'API Base URL',
        'api_key' => 'API Key *',
        'ai_model' => 'AI Model *',
        'install' => 'Install',
        'model_placeholder' => 'Enter AI model name (e.g., gpt-3.5-turbo, gpt-4, etc.)'
    ],
    'zh' => [
        'installation' => '安装',
        'fill_required_fields' => '请填写所有必填字段。',
        'database_connection_failed' => '数据库连接失败: ',
        'installation_completed' => '安装成功！正在跳转到主页...',
        'ai_website_installation' => 'lanxAI - 首个览星自研AI',
        'info_text' => '请填写您的数据库和API配置详细信息以完成安装。',
        'database_host' => '数据库主机 *',
        'database_name' => '数据库名称 *',
        'database_username' => '数据库用户名 *',
        'database_password' => '数据库密码 *',
        'api_base_url' => 'API基础URL',
        'api_key' => 'API密钥 *',
        'ai_model' => 'AI模型 *',
        'install' => '安装',
        'model_placeholder' => '输入AI模型名称（例如：gpt-3.5-turbo, gpt-4等）'
    ]
];

$current_text = $lang_texts[$lang];

$install_file = 'config/installed.txt';
if (file_exists($install_file)) {
    header('Location: index.php');
    exit;
}

$error_message = '';
$success_message = '';

if ($_POST) {
    $db_host = $_POST['db_host'] ?? '';
    $db_name = $_POST['db_name'] ?? '';
    $db_user = $_POST['db_user'] ?? '';
    $db_pass = $_POST['db_pass'] ?? '';
    $api_base_url = $_POST['api_base_url'] ?? 'https://apis.iflow.cn/v1';
    $api_key = $_POST['api_key'] ?? '';
    $ai_model = $_POST['ai_model'] ?? 'gpt-3.5-turbo';
    
    if (empty($db_host) || empty($db_name) || empty($db_user) || empty($api_key) || empty($ai_model)) {
        $error_message = $current_text['fill_required_fields'];
    } else {
        try {
            $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            $queries = [
                "CREATE TABLE IF NOT EXISTS prompts (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    prompt_text TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )",
                
                "CREATE TABLE IF NOT EXISTS chat_history (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_input TEXT NOT NULL,
                    ai_response TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )",
                
                "CREATE TABLE IF NOT EXISTS settings (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    setting_key VARCHAR(255) UNIQUE NOT NULL,
                    setting_value TEXT
                )"
            ];
            
            foreach ($queries as $query) {
                $pdo->exec($query);
            }
            
            $default_prompts = [
                "You are a helpful AI assistant.",
                "Please provide accurate and concise answers.",
                "Be polite and professional in your responses."
            ];
            
            $stmt = $pdo->prepare("INSERT INTO prompts (prompt_text) VALUES (?)");
            foreach ($default_prompts as $prompt) {
                $stmt->execute([$prompt]);
            }
            
            if (!is_dir('config')) {
                mkdir('config', 0755, true);
            }
            
            $config_content = "<?php\n";
            $config_content .= "\$db_host = '$db_host';\n";
            $config_content .= "\$db_name = '$db_name';\n";
            $config_content .= "\$db_user = '$db_user';\n";
            $config_content .= "\$db_pass = '$db_pass';\n";
            $config_content .= "\$pdo = new PDO('mysql:host='.\$db_host.';dbname='.\$db_name, \$db_user, \$db_pass);\n";
            $config_content .= "\$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n";
            $config_content .= "\$api_base_url = '$api_base_url';\n";
            $config_content .= "\$api_key = '$api_key';\n";
            $config_content .= "\$default_model = '$ai_model';\n";
            $config_content .= "?>";
            
            file_put_contents('config/config.php', $config_content);
            file_put_contents('config/installed.txt', date('Y-m-d H:i:s'));
            
            $success_message = $current_text['installation_completed'];
            
            header('Refresh: 3; URL=index.php');
        } catch (PDOException $e) {
            $error_message = $current_text['database_connection_failed'] . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="<?php echo $lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $current_text['installation']; ?></title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="password"], input[type="url"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007cba;
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            width: 100%;
            font-size: 16px;
        }
        button:hover {
            background-color: #005a87;
        }
        .error {
            color: red;
            margin-bottom: 15px;
        }
        .success {
            color: green;
            margin-bottom: 15px;
        }
        .info {
            background-color: #e7f3ff;
            padding: 10px;
            border-left: 4px solid #007cba;
            margin-bottom: 20px;
        }
        .language-switcher {
            float: right;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="language-switcher">
            <a href="?lang=en">English</a> | <a href="?lang=zh">中文</a>
        </div>
        
        <h1><?php echo $current_text['ai_website_installation']; ?></h1>
        
        <div class="info">
            <p><?php echo $current_text['info_text']; ?></p>
        </div>
        
        <?php if ($error_message): ?>
            <div class="error"><?php echo htmlspecialchars($error_message); ?></div>
        <?php endif; ?>
        
        <?php if ($success_message): ?>
            <div class="success"><?php echo htmlspecialchars($success_message); ?></div>
        <?php endif; ?>
        
        <form method="POST" action="">
            <div class="form-group">
                <label for="db_host"><?php echo $current_text['database_host']; ?></label>
                <input type="text" id="db_host" name="db_host" value="localhost" required>
            </div>
            
            <div class="form-group">
                <label for="db_name"><?php echo $current_text['database_name']; ?></label>
                <input type="text" id="db_name" name="db_name" required>
            </div>
            
            <div class="form-group">
                <label for="db_user"><?php echo $current_text['database_username']; ?></label>
                <input type="text" id="db_user" name="db_user" required>
            </div>
            
            <div class="form-group">
                <label for="db_pass"><?php echo $current_text['database_password']; ?></label>
                <input type="password" id="db_pass" name="db_pass" required>
            </div>
            
            <div class="form-group">
                <label for="api_base_url"><?php echo $current_text['api_base_url']; ?></label>
                <input type="url" id="api_base_url" name="api_base_url" value="https://apis.iflow.cn/v1" required>
            </div>
            
            <div class="form-group">
                <label for="api_key"><?php echo $current_text['api_key']; ?></label>
                <input type="text" id="api_key" name="api_key" value="sk-**********" required>
            </div>
            
            <div class="form-group">
                <label for="ai_model"><?php echo $current_text['ai_model']; ?></label>
                <input type="text" id="ai_model" name="ai_model" value="gpt-3.5-turbo" placeholder="<?php echo $current_text['model_placeholder']; ?>" required>
            </div>
            
            <button type="submit"><?php echo $current_text['install']; ?></button>
        </form>
    </div>
</body>
</html>
